import {UserRequester} from "@/api/api.js";
const UserRqster = new UserRequester();
import router from "@/router";
import {loginTIM} from '@/hooks/useTIM'
// import { showSuccessToast } from 'vant';
import { ElMessage } from 'element-plus'


const state = {
    //保存是否为已经登录的状态
    isLogined : false,
    token:'',
    //用户数据
    userData:{
        id:1,   //ID（唯一标识，后续用来登录TIM）
        nickname:'小租配齐官方',//昵称
        image:'',//头像
        phone:'',   //电话号码
        password:'',    //密码
    },

    //社交信息
    socialInfo:{
        fansNum:39, //粉丝
        followsNum:121, //关注
        news:12, //动态
    },

}


const actions = {
    //密码登录 
    pswLogin({commit,dispatch},userInfo){
        //发起请求
        
        let promise =  UserRqster.reqLoginPsw(userInfo);
        promise.then((result)=>{
            console.log(result);
            if (result.code == 1005){
                alert('账号或密码错误，请重试！')
            }
            else{
                localStorage.setItem('token',result.data.token)
                //获取用户信息后，派发commit修改state中的数据
                commit('LOGIN',result)
                //查询粉丝数
                dispatch('getFansNum');
                
            }         
        },(error)=>{
            alert('请求！请重试');
        })
    } ,
    //电话登录
    phoneLogin({commit,dispatch},userInfo){
        //发起请求
        
        let promise =  UserRqster.reqLoginPhone(userInfo);
        promise.then((result)=>{
            console.log(result);
            if (result.code == 1005){
                alert('验证码错误！')
            }
            else{
                localStorage.setItem('token',result.data.token)
                //获取用户信息后，派发commit修改state中的数据
                commit('LOGIN',result)
                //查询粉丝数
                dispatch('getFansNum');
                
            }         
        },(error)=>{
            alert('请求！请重试');
        })
    } ,
    //注册接口
    userRegister({commit,dispatch},userInfo){
        return UserRqster.reqUserReg(userInfo);
    },
    //查询粉丝数
    getFansNum({commit}){
        UserRqster.reqFansNum().then((res)=>{
            if (res.code == 200){
                commit('GET_FANS_NUM',res.data);
            }
        })
    },
    //获取验证码
    getCode({commit},phone){
        console.log(phone);
        return UserRqster.reqLoginCode(phone)
    }
}


const mutations = {
    //登录
    LOGIN(state,result){
        //修改登录状态为成功
        state.isLogined = true;
        //保存token
        state.token = result.token;
        //修改得到用户数据
        state.userData = result.data.user;
        //登录TIM
        loginTIM(state.userData.id);
        ElMessage({
            message: '登录成功',
            type: 'success',
          })
        router.push('home')
    },

    //查询粉丝数
    GET_FANS_NUM(state,fanNum){
        state.socialInfo.fansNum =fanNum;
    }
}

const getters = {
    
}


export default {
    namespaced:true,
    state,
    getters,
    actions,
    mutations,
}